import asyncio
import time
import datetime

# https://docs.python.org/zh-cn/3/library/asyncio-task.html#id5

# async def main():
#     print('hello')
#     await asyncio.sleep(1)
#     print('world')
#
#
# asyncio.run(main())

async def say_after(delay, what):
    await asyncio.sleep(delay)
    print(what)

# async def main():
#     print(f"started at {time.strftime('%X')}")
#
#     await say_after(1, 'hello')
#     await say_after(2, 'world')
#
#     print(f"finished at {time.strftime('%X')}")
#
# asyncio.run(main())

# asyncio.create_task() 函数用来并发运行作为 asyncio 任务 的多个协程。
# 并发版本的
# async def main():
#     print(f"started at {time.strftime('%X')}")
#     task1 = asyncio.create_task(say_after(1, 'hello'))
#     task2 = asyncio.create_task(say_after(2, 'world'))
#
#     await task1
#     await task2
#     print(f"finished at {time.strftime('%X')}")
#
# asyncio.run(main())

# async def display_date():
# #     loop = asyncio.get_running_loop()
# #     end_time = loop.time() + 5.0
# #     while True:
# #         print(datetime.datetime.now())
# #         if (loop.time() + 1.0) >= end_time:
# #             break
# #         await asyncio.sleep(1)
# #
# # asyncio.run(display_date())

# async def factorial(name, number):
#     f = 1
#     for i in range(2, number + 1):
#         print(f"Task {name}: Compute factorial({i})...")
#         await asyncio.sleep(1)
#         f *= i
#     print(f"Task {name}: factorial({number}) = {f}")
#
# async def main():
#     await asyncio.gather(
#         factorial("A", 2),
#         factorial("B", 3),
#         factorial("C", 4),
#     )

# asyncio.run(main())
# 屏蔽取消操作

# 超时¶
# coroutine asyncio.wait_for(aw, timeout, *, loop=None)

# async def eternity():
#     # Sleep for one hour
#     await asyncio.sleep(3600)
#     print('yay!')
#
# async def main():
#     # Wait for at most 1 second
#     try:
#         await asyncio.wait_for(eternity(), timeout=1.0)
#     except asyncio.TimeoutError:
#         print('timeout!')
#
# asyncio.run(main())

# async def foo():
#     return 42
#
# task = asyncio.create_task(foo())
# done, pending = await asyncio.wait({task})
#
# if task in done:
#     print("ok")

# def blocking_io():
#     print(f"start blocking_io at {time.strftime('%X')}")
#     # Note that time.sleep() can be replaced with any blocking
#     # IO-bound operation, such as file operations.
#     time.sleep(1)
#     print(f"blocking_io complete at {time.strftime('%X')}")
#
# async def main():
#     print(f"started main at {time.strftime('%X')}")
#
#     await asyncio.gather(
#         asyncio.to_thread(blocking_io),
#         asyncio.sleep(1))
#
#     print(f"finished main at {time.strftime('%X')}")
#
#
# asyncio.run(main()) from peewee import *